package com.ddstation.sewage.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import com.ddstation.common.service.DataDictionaryService;
import com.ddstation.crm.menu.entity.DtInvsManageInstitutionMenuEntity;
import com.ddstation.crm.menu.service.MenuService;
import com.ddstation.exam.entity.DtHealthManageInstitutionGroupEntity;
import com.ddstation.exchange.service.DtHealthManageInstitutionGroupService;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.prescription_violate.model.ViolateDetailResModel;
import com.ddstation.util.getDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddstation.common.service.ImageService;
import com.ddstation.common.util.DateUtil;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.sewage.model.SewageTestResModel;
import com.ddstation.sewage.model.SewageTestSearchParModel;
import com.ddstation.sewage.service.SewageService;
import com.ddstation.sewage.service.SewageTestReportService;

@Controller
public class SewageTestReportController {
	
	/**
	 * 诊所污水检测查询页面 跳转
	 * 
	 * @param
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_sewage_test_report.do")
	public String sewageInitEvent(
			Model model, HttpSession session) {

		// 从session获取基础数据
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			return "forward:login?timeout=true"; // session 过期
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取当天
		Calendar cale = Calendar.getInstance();
		String lastday = format.format(cale.getTime());
		//取开始时间
		String firstday = getDateUtil.getFirstday(null);

		SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM");
		// 获取当天
		String dateYm = format2.format(cale.getTime());
		String[] data =dateYm.split("-");
		List<Integer> yearList=new ArrayList<>();
		for (int i=0;i<10;i++){
			Integer year=Integer.parseInt(data[0]);
			year-=i;
			yearList.add(year);
		}
		Collections.reverse(yearList);
        // 获取前月的最后一天
		model.addAttribute("dtFrom", firstday); 	// 开始时间
		model.addAttribute("dtTo", lastday); 		// 当月的最后一天
		model.addAttribute("yearList", yearList); 	// 前十年列表
		model.addAttribute("year",data[0]);			//当前年
		model.addAttribute("month",data[1]);			//当前月份
		model.addAttribute("businessSubType", "303");// 默认污水报告

		//一级医疗机构类别
		List<MaDataDictionaryEntity> typeFirstList = dataDictionaryService.getCodeList("institution_type_first");

		model.addAttribute("typeFirstList", typeFirstList);

		//获取二级菜单目录
		String firstMenuUrl = "invs_sewage_test_report.do";
//		List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getJurisdictionMenus(), firstMenuUrl);
		List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getWorkbenchMenus(), firstMenuUrl);
		if(secondMenus == null){
			//无访问权限【跳转地址修改】
			return "forward:login?timeout=true";
		}
		model.addAttribute("secondMenus", secondMenus);

		return "pc/sewage/test_report";
	}
	
	/**
	 * 查询数据接口
	 * 
	 * @param SewageTestSearchParModel  页面输入的条件
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_sewage_test_report.do/load", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadSewageTestReportListEvent(
			@RequestBody SewageTestSearchParModel _in,
			HttpSession session) throws ParseException {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
		// 日期check
		if ( StringUtils.isBlank(_in.getDtFrom()) 
				&& StringUtils.isBlank(_in.getDtTo()) 
				&& StringUtils.isBlank(_in.getDateYm())){
			ret.put("errMsg", "没有输入查询日期！");
			return ret;
		} 
		
		// 查询年月进来的情况【即综合查询页面调用时】
        if ( StringUtils.isNotBlank(_in.getDateYm())   ){
			String[] beginEndDate = DateUtil.getBeginEndDate(_in.getDateYm());
			if ( beginEndDate == null ){
				ret.put("errMsg", "系统出错，传入参数：年月错误！");
				return ret;
			}
			_in.setDtFrom(beginEndDate[0]);
			_in.setDtTo(beginEndDate[1]);
		}
		
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
        // session中卫监所的基础信息传入service
        _in.setInvsInstitutionId(loginData.getInstitution().getId());
        //如果查询某机构数据
		if(_in.getInstitutionId() != null){
			//查询机构全部子ID
			DtHealthManageInstitutionGroupEntity entity = new DtHealthManageInstitutionGroupEntity();
			entity.setParentInstitutionId(_in.getInstitutionId());
			List<DtHealthManageInstitutionGroupEntity> dtHealthManageInstitutionGroupList = dtHealthManageInstitutionGroupService.select(entity);
			//设置机构ID集合，必定存在父机构ID
			List<String> institutionIdList = new ArrayList<>();
			institutionIdList.add(_in.getInstitutionId());
			if(dtHealthManageInstitutionGroupList != null && dtHealthManageInstitutionGroupList.size() > 0){
				//存在子ID则全部加入in条件查询
				for(DtHealthManageInstitutionGroupEntity dtHealthManageInstitutionGroup:dtHealthManageInstitutionGroupList){
					institutionIdList.add(dtHealthManageInstitutionGroup.getChildInstitutionId());
				}
			}
			_in.setInstitutionIdList(institutionIdList);
			//去除原机构ID条件
			_in.setInstitutionId(null);
			// 查询实施
			List<SewageTestResModel> datalist = sewageTestReportService.searchSewageTestReportList(_in);
			//替换展示 机构/科室 名称
			for(SewageTestResModel data:datalist){
				if(institutionIdList.get(0).equals(data.getInstitutionId())){
					data.setInstitutionShortName(data.getInstitutionName());
				}
			}
			ret.put("datalist",datalist);
		}else{
			// 查询实施
			List<SewageTestResModel> datalist = sewageTestReportService.searchSewageTestReportList(_in);
			ret.put("datalist",datalist);
		}
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}
	
	/**
	 * 查询诊所污水检测数据接口
	 * 
	 * @param SewageFormParModel  页面输入的条件
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_sewage_test_report.do/load_image", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadSewageTestReportImageListEvent(
			@RequestBody SewageTestSearchParModel _in,
			HttpSession session) throws ParseException {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
        // session中卫监所的基础信息传入service
        if ( StringUtils.isBlank(_in.getReportImgId()) || 
        		StringUtils.isEmpty(_in.getReportImgId())){
        	ret.put("errMsg", "系统出错，请联系客服！错误信息：参数不足。没有imageid");
        	return ret;
        }
        // 访问权限check(防止异常调用)
 		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),_in.getInstitutionId()) ){
 			ret.put("errMsg", "对该诊所没有访问权限！");
 			return ret;
 		}
        // 查询实施
		ret.put("imagelist",imageService.fetchImage(_in.getReportImgId()));

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	@Inject private MenuService menuService;
	@Inject private SewageTestReportService sewageTestReportService;
	@Inject private SewageService sewageService;
	@Inject private ImageService imageService;
	@Inject private DtHealthManageInstitutionGroupService dtHealthManageInstitutionGroupService;
	@Inject private DataDictionaryService dataDictionaryService;
}
